﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

namespace dzs.Web.Outstorage
{
    public partial class EmergencyOut : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Session["login"] != null)
                {
                    DataSet ds = Session["login"] as DataSet;
                    int roles_id = Convert.ToInt32(ds.Tables[0].Rows[0]["roles_id"].ToString());
                    int user_id = Convert.ToInt32(ds.Tables[0].Rows[0]["user_id"].ToString());

                    BindDDL(user_id);
                }
            }
        }

        private void BindDDL(int cguid)
        {
            string strWhere = " cguid=" + cguid;

            DataSet ds_project = new dzs.BLL.materialinfo().GetDistinctProidList(strWhere);

            this.ddl_project.DataSource = ds_project;
            this.ddl_project.DataTextField = "projectname";
            this.ddl_project.DataValueField = "proid";
            this.ddl_project.DataBind();
            this.ddl_project.Items.Insert(0, new ListItem("---未选择---", "-1"));
        
        }

        protected void btn_selectProject_Click(object sender, EventArgs e)
        {
            BindGV();
        }

        private void BindGV()
        {
            if (this.ddl_project.SelectedValue == "-1")
            {
                ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('请选择出库项目！');</script>");
                return;
            }
         
            dzs.BLL.inventory ven = new BLL.inventory();

            string where = " proid='"+this.ddl_project.SelectedValue+"' ";
            if (!string.IsNullOrEmpty(this.txt_material.Text))
            {
                where += " and material like '%" + this.txt_material.Text + "%' ";

            }

            DataSet ds = ven.GetMaterialInventoryOutStorageList(where);

            this.GridView1.DataSource = ds;
            this.GridView1.DataBind();
        }
        //添加
        protected void btn_add_Click(object sender, EventArgs e)
        {
            #region 验证是否填写
            if (string.IsNullOrEmpty(this.txt_out_storage_Estimate.Text))
            {
                ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('请填写出库时间！');</script>");
                return;
            }
            if (string.IsNullOrEmpty(this.txt_receive_address.Text))
            {
                ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('请填写收货地点！');</script>");
                return;
            }
            if (string.IsNullOrEmpty(this.txt_receive_userName.Text))
            {
                ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('请填写收货人！');</script>");
                return;
            }
            if (string.IsNullOrEmpty(this.txt_receive_userPhone.Text))
            {
                ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('请填写收货人电话！');</script>");
                return;
            }
            #endregion

            string msg = CheckCboList();

            if (!string.IsNullOrEmpty(msg))
            {
                ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('" + msg + "');</script>");
            }
            else
            {
                if (Session["login"] != null)
                {
                    DataSet ds = Session["login"] as DataSet;

                    int user_id = Convert.ToInt32(ds.Tables[0].Rows[0]["user_id"].ToString());

                    BindGV2(user_id);
                    BindGV();
                }
                else
                {
                    Maticsoft.Common.MessageBox.Show(this, "由于长时间未操作，登录信息已过期，请重新登陆!");
                }

            }

            this.ddl_project.Enabled = false;
        }

        //绑定出库清单
        private void BindGV2(int user_id)
        {
            //获取选择的出库清单
            List<dzs.Model.emergencyOut> li = GetCboList(user_id);
            //将前边页已选择的出库清单加入
            if (Session["emergencyOut"] != null)
            {
                List<dzs.Model.emergencyOut> li_session = Session["emergencyOut"] as List<dzs.Model.emergencyOut>;

                foreach (dzs.Model.emergencyOut o in li_session)
                {
                    li.Add(o);
                }

                Session["emergencyOut"] = li;
            }
            else
            {
                Session["emergencyOut"] = li;
            }

            this.GridView2.DataSource = this.GetCboDataSet(li);
            this.GridView2.DataBind();
        }

        //验证实际剩余数量与出库数量之差
        private string CheckCboList()
        {
            string msg = "";

            for (int i = 0; i < this.GridView1.Rows.Count; i++)
            {
                CheckBox cbo = this.GridView1.Rows[i].FindControl("cbo_check") as CheckBox;

                if (cbo != null && cbo.Checked)
                {
                    TextBox txt_out_storage_count = this.GridView1.Rows[i].FindControl("txt_out_storage_count") as TextBox;//预出库数量
                    Label lbl_material_id = this.GridView1.Rows[i].FindControl("lbl_material_id") as Label;//物料ID
                    Label lbl_realCount = this.GridView1.Rows[i].FindControl("lbl_realCount") as Label;//实际剩余数量

                    decimal out_count = 0;
                    decimal real_count = 0;
                    int mid = 0;

                    try
                    {
                        if (!string.IsNullOrEmpty(txt_out_storage_count.Text))
                        {
                            out_count = Convert.ToDecimal(txt_out_storage_count.Text);
                        }
                        else
                        {
                            msg += @"\n 请填写应急出库数量！";
                        }
                    }
                    catch (Exception)
                    {

                        msg += @"\n 应急出库量请填写数字！";
                    }

                    if (!string.IsNullOrEmpty(lbl_realCount.Text))
                    {
                        real_count = Convert.ToDecimal(lbl_realCount.Text);
                    }
                    if (!string.IsNullOrEmpty(lbl_material_id.Text))
                    {
                        mid = Convert.ToInt32(lbl_material_id.Text);
                    }

                    if (real_count - out_count < 0)
                    {
                        dzs.Model.materialinfo m = new dzs.BLL.materialinfo().GetModel(mid);

                        msg += @"\n “" + m.material + "”应急出库数量大于实际剩余数量，请重新填写！";
                    }


                }
            }

            return msg;
        }
        //验证出库单
        private string CheckOutList(List<dzs.Model.emergencyOut> li)
        {
            string msg = "";

            decimal count = 0;

            for (int i = 0; i < this.GridView1.Rows.Count; i++)
            {
                Label lbl_count = this.GridView1.Rows[i].FindControl("lbl_realCount") as Label;
                Label lbl_material_id = this.GridView1.Rows[i].FindControl("lbl_material_id") as Label;//物料ID
                Label lbl_material = this.GridView1.Rows[i].FindControl("lbl_material") as Label;//物料描述

                if (!string.IsNullOrEmpty(lbl_count.Text) && !string.IsNullOrEmpty(lbl_material_id.Text))
                {
                    count = Convert.ToDecimal(lbl_count.Text.Trim());
                    foreach (dzs.Model.emergencyOut o in li)
                    {
                        if (o.mid.Value == Convert.ToInt32(lbl_material_id.Text))
                        {
                            count = count - o.emergencyNums.Value;
                        }
                    }

                    if (count < 0)
                    {
                        msg += @"\n “" + lbl_material.Text + "”";
                    }

                }

            }

            if (!string.IsNullOrEmpty(msg))
            {
                msg += @"\n 申请出库量大于实际剩余量，请重新填写出库单！";
            }


            return msg;
        }

        private List<dzs.Model.emergencyOut> GetCboList(int user_id)
        {
            List<dzs.Model.emergencyOut> li = new List<Model.emergencyOut>();

            for (int i = 0; i < this.GridView1.Rows.Count; i++)
            {
                CheckBox cbo = this.GridView1.Rows[i].FindControl("cbo_check") as CheckBox;

                if (cbo != null && cbo.Checked)
                {
                    TextBox txt_out_storage_count = this.GridView1.Rows[i].FindControl("txt_out_storage_count") as TextBox;//预出库数量
                   
                    Label lbl_material_id = this.GridView1.Rows[i].FindControl("lbl_material_id") as Label;//物料ID
                    Label lbl_realCount = this.GridView1.Rows[i].FindControl("lbl_realCount") as Label;//实际剩余数量
                    Label lbl_material = this.GridView1.Rows[i].FindControl("lbl_material") as Label;//物料描述
                    Label lbl_unit = this.GridView1.Rows[i].FindControl("lbl_unit") as Label;//数量单位
                    Label lbl_proid = this.GridView1.Rows[i].FindControl("lbl_proid") as Label;//项目编号
                    Label lbl_projectname = this.GridView1.Rows[i].FindControl("lbl_projectname") as Label;//项目名称
                     Label lbl_inid = this.GridView1.Rows[i].FindControl("lbl_inid") as Label;//库存ID

                    dzs.Model.emergencyOut o = new Model.emergencyOut();

                    o.mid = int.Parse(lbl_material_id.Text);
                    o.receive_address = txt_receive_address.Text;
                    o.receive_userName = txt_receive_userName.Text;
                    o.receive_userPhone = txt_receive_userPhone.Text;
                    o.sourceProid = lbl_proid.Text;
                    o.sourceProjectName = lbl_projectname.Text;
                    o.unit = lbl_unit.Text;
                    o.inid = int.Parse(lbl_inid.Text);
                    o.emergencyNums = decimal.Parse(txt_out_storage_count.Text);
                    o.emergencyTime = DateTime.Parse(txt_out_storage_Estimate.Text);
                    o.material = lbl_material.Text;
                    o.user_id = user_id;

                    li.Add(o);
                    
                }
            }

            return li;
        }
        //翻页
        protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            this.GridView1.PageIndex = e.NewPageIndex;
            BindGV();
        }

        //重新填写出库单
        protected void btn_re_Click(object sender, EventArgs e)
        {
            Session.Remove("emergencyOut");
            if (Session["login"] != null)
            {
                DataSet ds = Session["login"] as DataSet;

                int user_id = Convert.ToInt32(ds.Tables[0].Rows[0]["user_id"].ToString());

                BindGV2(user_id);
                BindGV();
            }

            this.ddl_project.Enabled = true;
        }

        private DataTable GetCboDataSet(List<dzs.Model.emergencyOut> li)
        {
            DataTable dt = new DataTable();

            dt.Columns.Add("out_storage_count", Type.GetType("System.String"));//应急出库数量
            dt.Columns.Add("material", Type.GetType("System.String"));//物料描述
            dt.Columns.Add("unit", Type.GetType("System.String"));//数量单位
            dt.Columns.Add("projectname", Type.GetType("System.String"));//项目名称
            dt.Columns.Add("proid", Type.GetType("System.String"));//项目编号
            dt.Columns.Add("mid", Type.GetType("System.String"));//物料ID

            foreach (dzs.Model.emergencyOut o in li)
            {
                DataRow row = dt.NewRow();
                row["out_storage_count"] = o.emergencyNums;
                row["material"] = o.material;
                row["unit"] = o.unit;
                row["proid"] = o.sourceProid;
                row["projectname"] = o.sourceProjectName;
                row["mid"] = o.mid.ToString();

                dt.Rows.Add(row);
            }

            return dt;
        }

        //提交
        protected void btn_submit_Click(object sender, EventArgs e)
        {
            if (Session["emergencyOut"] != null)
            {
                string batchId = "yj"+this.ddl_project.SelectedValue + "TIME" + System.DateTime.Now.ToString("yyyyMMddHHmmssffff");//应急出库单号

                List<dzs.Model.emergencyOut> li = Session["emergencyOut"] as List<dzs.Model.emergencyOut>;

                string msg = this.CheckOutList(li);//验证所填写出库单数量是否超出实际剩余量

                if (string.IsNullOrEmpty(msg))
                {
                    dzs.BLL.inventory im = new BLL.inventory();
                    dzs.BLL.emergencyOut om = new BLL.emergencyOut();

                    foreach (dzs.Model.emergencyOut o in li)
                    {
                        o.emergencyNo = batchId;//出库清单号

                        dzs.Model.inventory i = im.GetModel(o.inid.Value);

                        i.nums = i.nums - o.emergencyNums;//库存量减去应急出库量

                        im.Update(i);

                        om.Add(o);
                    }

                    Session.Remove("emergencyOut");
                    if (Session["login"] != null)
                    {
                        DataSet ds = Session["login"] as DataSet;

                        int user_id = Convert.ToInt32(ds.Tables[0].Rows[0]["user_id"].ToString());

                        BindGV2(user_id);
                        BindGV();
                    }

                    //ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('操作成功！您的出库清单号："+batchId+"');</script>");
                    Maticsoft.Common.MessageBox.Show(this, "操作成功！您的应急出库清单号：" + batchId);
                }
                else
                {
                    Maticsoft.Common.MessageBox.Show(this, msg);
                }


            }
            else
            {
                Maticsoft.Common.MessageBox.Show(this, "由于长时间未操作，信息已过期，请重新登陆!");
            }

        }

    }
}